# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '23': {
        #  畅通支付  支付宝H5 2.4% 50-10000 dwc
        'API_KEY': '5bd730d56871d4f6c4bacbbc940d7cd7',
        'gateway': 'http://www.fuyu586.com/api/order/add',
        'query_gateway': 'http://www.fuyu586.com/api/order/sel',
    },
    '22': {
        #  畅通支付  支付宝H5 2.4% 50-10000 witch
        'API_KEY': '9c93db9444fa93ad5281345bb9dfc1e7',
        'gateway': 'http://www.fuyu586.com/api/order/add',
        'query_gateway': 'http://www.fuyu586.com/api/order/sel',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign':
            s += '%s=%s&' % (k, parameter[k])
    s += 'token=%s' % key
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("changtongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)
    else:
        return True


def _get_pay_type(service):
    # 支付方式：AlipayH5表示支付宝H5支付，QqpayQrcode表示QQ扫码支付，WxpayQrcode表示微信扫码支付，YsfpayQrcode表示云闪付扫码支付
    if service == 'alipay_h5':
        return 'AlipayH5'
    elif service == 'qq_scan':
        return 'QqpayQrcode'
    elif service == 'wechat_scan':
        return 'WxpayQrcode'
    elif service == 'cloudpay_scan':
        return 'YsfpayQrcode'
    return 'AlipayH5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('organizationId', app_id),
        ('payment', _get_pay_type(service)),
        ('organizationOrderCode', str(pay.id)),
        ('orderPrice', '%.2f' % pay_amount),
        ('notifyUrl', '{}/pay/api/{}/changtongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("changtongpay create: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['organizationOrderCode'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("changtongpay create charge data: %s %s", response.status_code, response.text)
    verify_sign(json.loads(response.text)['data'], api_key)
    return {'charge_info': json.loads(response.text)['data']['payUrl']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("changtongpay notify data: %s, order_id is: %s", data, data['organizationOrderCode'])
    verify_sign(data, api_key)
    pay_id = data['organizationOrderCode']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('changtongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderPayStatus'])
    trade_no = str(data['orderCode'])
    total_fee = float(data['orderPrice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 订单支付状态：0未付款，1已付款
    if trade_status == '1':
        _LOGGER.info('changtongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('organizationId', app_id),
        ('organizationOrderCode', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("changtongpay query data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['organizationOrderCode'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("changtongpay query rsp data: %s", response.text)
    verify_sign(json.loads(response.text)['data'], api_key)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        trade_status = str(data['orderPayStatus'])
        trade_no = str(data['orderCode'])
        total_fee = float(data['orderPrice'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 订单支付状态：0未付款，1已付款
        if trade_status == '1':
            _LOGGER.info('changtongpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('changtongpay data error, status_code: %s', response.status_code)
